package com.xxx.springboot.service.impl;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xxx.springboot.service.TokenService;
import com.xxx.springboot.util.CommonUtil;

/**
 * 1.幂等性处理
 * token服务实现类
 */
@Service
public class TokenServiceImpl implements TokenService {
	
	private static final String TOKEN_PREFIX = "token:";
	
	private static final String TOKEN_NAME = "TK";

	@Autowired
    private RedisService redisService;
	
	/**
	 * 创建token
	 */
	@Override
	public String createToken() {
        try {
        	StringBuilder token = new StringBuilder();
        	String uuid = CommonUtil.getUUID(); // 通过uuid来产生随机数，作为token
            token.append(TOKEN_PREFIX).append(uuid);
            redisService.setEx(token.toString(), token.toString(), 1000 * 10L); // 过期时间：10秒
            if (StringUtils.isNotEmpty(token.toString())) {
                return token.toString();
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
	}

	/**
	 * 校验token
	 */
	@Override
	public boolean checkToken(HttpServletRequest request) throws Exception {
		String token = request.getHeader(TOKEN_NAME); // 从header里获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(TOKEN_NAME); // 从传入的参数里获取token
            if (StringUtils.isBlank(token)) {
                throw new RuntimeException("缺少token");
            }
        }

        // 判断token在redis中是否存在
        if (!redisService.exists(token)) { // 不存在
            throw new RuntimeException("token不存在或已失效");
        }

        // 删除token
        boolean remove = redisService.remove(token);
        if (!remove) {
            throw new RuntimeException("删除token失败");
        }
        return true;
	}

}
